# 天气API路由
import requests
from fastapi import APIRouter, Query
from .config import API_WEATHER

weather_bp = APIRouter(prefix="/weather")

# 新知天气API基础URL
BASE_URL = "https://api.seniverse.com/v3"

@weather_bp.get('/now')
async def get_current_weather(location: str = Query(default="beijing")):
    """获取实时天气数据"""
    # 构建API请求URL
    url = f"{BASE_URL}/weather/now.json"
    params = {
        'key': API_WEATHER,
        'location': location,
        'language': 'zh-Hans',
        'unit': 'c'
    }
    
    try:
        response = requests.get(url, params=params)
        response.raise_for_status()  # 如果请求失败，抛出异常
        return response.json()
    except Exception as e:
        return {"error": str(e)}

@weather_bp.get('/forecast')
async def get_weather_forecast(location: str = Query(default="beijing")):
    """获取未来3天天气预报"""
    # 构建API请求URL
    url = f"{BASE_URL}/weather/daily.json"
    params = {
        'key': API_WEATHER,
        'location': location,
        'language': 'zh-Hans',
        'unit': 'c',
        'start': 0,
        'days': 3
    }
    
    try:
        response = requests.get(url, params=params)
        response.raise_for_status()  # 如果请求失败，抛出异常
        return response.json()
    except Exception as e:
        return {"error": str(e)}

@weather_bp.get('/search')
async def search_location(q: str = Query(..., description="搜索关键词，可以是城市名称、ID、IP或经纬度"), limit: int = Query(10, description="每页结果数"), offset: int = Query(0, description="结果偏移量")):
    """搜索城市位置信息"""
    # 构建API请求URL
    url = f"{BASE_URL}/location/search.json"
    params = {
        'key': API_WEATHER,
        'q': q,
        'language': 'zh-Hans',
        'limit': limit,
        'offset': offset
    }
    
    try:
        response = requests.get(url, params=params)
        response.raise_for_status()  # 如果请求失败，抛出异常
        return response.json()
    except Exception as e:
        return {"error": str(e)}